package com.eleadmin.common.system.controller;

import com.eleadmin.common.core.web.BaseController;
import com.eleadmin.common.system.entity.CreditRating;
import com.eleadmin.common.system.entity.Order;
import com.eleadmin.common.system.service.CommentService;
import com.eleadmin.common.system.entity.Comment;
import com.eleadmin.common.system.param.CommentParam;
import com.eleadmin.common.core.web.ApiResult;
import com.eleadmin.common.core.web.PageResult;
import com.eleadmin.common.core.web.PageParam;
import com.eleadmin.common.core.web.BatchParam;
import com.eleadmin.common.core.annotation.OperationLog;
import com.eleadmin.common.system.service.CreditRatingService;
import com.eleadmin.common.system.service.OrderService;
import com.eleadmin.common.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 留言表控制器
 *
 * @author EleAdmin
 * @since 2025-04-28 22:40:00
 */
@Api(tags = "留言表管理")
@RestController
@RequestMapping("/system/comment")
public class CommentController extends BaseController {
    @Resource
    private CommentService commentService;
    @Resource
    private UserService userService;
    @Resource
    private OrderService orderService;
    @Resource
    private CreditRatingService creditRatingService;

    @OperationLog
    @ApiOperation("分页查询留言表")
    @GetMapping("/page")
    public ApiResult<PageResult<Comment>> page(CommentParam param) {
        PageResult<Comment> commentPageResult = commentService.pageRel(param);
        commentPageResult.getList().forEach(comment -> {
            if (comment.getUserId() != null) {
                comment.setUserName(userService.getById(comment.getUserId()).getNickname());
            } else {
                comment.setUserName("无");
            }
            if (comment.getAcceptId() != null) {
                comment.setAcceptName(userService.getById(comment.getAcceptId()).getNickname());
            } else {
                comment.setAcceptName("无");
            }
            comment.setOrderName(orderService.getById(comment.getOrderId())==null?"":orderService.getById(comment.getOrderId()).getName());

        });
        return success(commentPageResult);

    }


    @OperationLog
    @ApiOperation("查询全部留言表")
    @GetMapping()
    public ApiResult<List<Comment>> list(CommentParam param) {
        List<Comment> comments = commentService.listRel(param);
        comments.forEach(comment -> {
            if (comment.getUserId() != null) {
                comment.setUserName(userService.getById(comment.getUserId()).getNickname());
            } else {
                comment.setUserName("无");
            }
            if (comment.getAcceptId() != null) {
                comment.setAcceptName(userService.getById(comment.getAcceptId()).getNickname());
            } else {
                comment.setAcceptName("无");
            }
            comment.setOrderName(orderService.getById(comment.getOrderId())==null?"":orderService.getById(comment.getOrderId()).getName());

        });
        return success(comments);

    }


    @OperationLog
    @ApiOperation("根据id查询留言表")
    @GetMapping("/{id}")
    public ApiResult<Comment> get(@PathVariable("id") Integer id) {
        return success(commentService.getById(id));

    }


    @OperationLog
    @ApiOperation("添加留言表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Comment comment) {
        //如果是用户角色，获取当前评论的订单，通过订单获取骑手id
        Integer orderId = comment.getOrderId();
        Order order = orderService.getById(orderId);
        Integer creditRatingUserId ;
        //判断当前用户角色
        if (getLoginUser().getRoles().get(0).getRoleCode().equals("user")) {
            comment.setUserId(getLoginUser().getUserId());
            //判断当前登录用户是否是订单发起人
            if (Objects.equals(order.getUserId(), comment.getUserId())) {
                creditRatingUserId = order.getAcceptId();
            }else {//
                creditRatingUserId = order.getUserId();
            }

        } else {
            comment.setAcceptId(getLoginUser().getUserId());
            if (Objects.equals(order.getAcceptId(), comment.getUserId())) {
                creditRatingUserId = order.getUserId();
            }else {//
                creditRatingUserId = order.getAcceptId();
            }
        }

        //获取评分
        CreditRating creditRating = creditRatingService.getByUserId(creditRatingUserId);
        Integer creditRatingScore = creditRating.getCreditRatingScore();
        //获取用户评分
        Integer star = comment.getStar();
        if (star < 3) {
            //如果用户评分小于3，扣减信用分
            if (creditRatingScore == 0) {
                creditRatingScore = 0;
            } else {
                creditRatingScore = creditRatingScore - 1;
            }
        } else {
            if (creditRatingScore == 100) {
                creditRatingScore = 100;
            } else {
                //如果用户评分大于3，增加信用分
                //当信用分达到70、80、90时，奖励信用分为1
                if (creditRatingScore == 70 || creditRatingScore == 80 || creditRatingScore == 90) {
                    creditRatingScore = creditRatingScore + 1;
                }
                //如果用户评分大于3，增加信用分
                creditRatingScore = creditRatingScore + 1;
            }


        }
        if (creditRatingScore  <= 70) {
            creditRating.setCreditRating("一般");
        }else if (creditRatingScore  <= 80) {
            creditRating.setCreditRating("良好");
        }else if (creditRatingScore  > 90 ) {
            creditRating.setCreditRating("优秀");
        }

        creditRating.setCreditRatingScore(creditRatingScore);
        creditRatingService.updateById(creditRating);
        if (commentService.save(comment)) {
            return success("评价成功");
        }
        return fail("评价失败");
    }


    @OperationLog
    @ApiOperation("修改留言表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Comment comment) {
        if (commentService.updateById(comment)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }


    @OperationLog
    @ApiOperation("删除留言表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (commentService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }


    @OperationLog
    @ApiOperation("批量添加留言表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Comment> list) {
        if (commentService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }


    @OperationLog
    @ApiOperation("批量修改留言表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Comment> batchParam) {
        if (batchParam.update(commentService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }


    @OperationLog
    @ApiOperation("批量删除留言表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (commentService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
